﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SuuntoAmbitConnector;
using EndomondoWebAccess;

namespace Suunto2EndomondoTestApp
{
    /// <summary>
    /// Interaction logic for Suunto2EndomondoTestApplication.xaml
    /// </summary>
    public partial class Suunto2EndomondoTestApplication : Window
    {

        private FileInfo suuntoFile;
        private Workout suuntoWorkout;

        public Suunto2EndomondoTestApplication()
        {
            InitializeComponent();
        }

        private void selectSuuntoFile_Click(object sender, RoutedEventArgs e)
        {            
            suuntoWorkout = null;
            suuntoFile = null;

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document";
            dlg.DefaultExt = ".xml";
            dlg.Filter = "XML documents (.xml)|*.xml";

            if ((bool)dlg.ShowDialog())
            {
                this.selectedSuuntoFileLog.Text = "The Suunto file is beeing parsed. Please wait...";
                
                try
                {
                    suuntoFile = new FileInfo(dlg.FileName);
                    var suuntoFileReader = new SuuntoAmbitFileReader(suuntoFile.DirectoryName);
                    suuntoFileReader.LoadWorkoutFile(suuntoFile.Name);
                    suuntoWorkout = suuntoFileReader.CreateWorkoutObject();

                    this.dateTextBox.Text = suuntoWorkout.StartDate.ToString("yyyy-MM-dd");
                    this.activityTextBox.Text = suuntoWorkout.Activity.ToString();
                    this.distanceTextBox.Text = string.Format("{0}.{1}", suuntoWorkout.GetDistanceKilometerPart(), suuntoWorkout.GetDistanceMeterPart());
                    this.durationTextBoxHours.Text = suuntoWorkout.GetDurationHourPart().ToString();
                    this.durationTextBoxMinutes.Text = suuntoWorkout.GetDurationMinutePart().ToString();
                    this.durationTextBoxSeconds.Text = suuntoWorkout.GetDurationSecondPart().ToString();
                    this.commentTextBox.Text = suuntoWorkout.Comment;

                    this.selectedSuuntoFileLog.Text = "Parsing successful.";
                }
                catch (Exception ex)
                {
                    this.selectedSuuntoFileLog.Text = ex.Message;
                }                                                
            }
        }

        private void createManualWorkoutFromFile_Click(object sender, RoutedEventArgs e)
        {
            this.createdWorkoutLog.Text = "The workout is beeing created. Please wait...";
            
            if (string.IsNullOrEmpty(this.usernameTextBox.Text) || string.IsNullOrEmpty(this.passwordTextBox.Password))
            {
                this.createdWorkoutLog.Text = "Username and password are required.";
                return;
            }

            if (suuntoFile == null)
            {
                if (string.IsNullOrEmpty(this.dateTextBox.Text))
                {
                    createdWorkoutLog.Text = "Cannot find a loaded Suunto Ambit file or valid user defined input data. Please select a file first or enter data accordingly.";
                    return;
                }
                else
                {
                    try
                    {
                        DateTime startDate;
                        if (!DateTime.TryParse(this.dateTextBox.Text, out startDate))
                        {
                            createdWorkoutLog.Text = "Cannot convert the entered start date. Are you using the correct format yyyy-MM-dd?";
                            return;
                        }
                        var activity = string.IsNullOrEmpty(this.activityTextBox.Text) ? 1 : Int16.Parse(this.activityTextBox.Text);
                        var hours = string.IsNullOrEmpty(this.durationTextBoxHours.Text) ? 0 : Int16.Parse(this.durationTextBoxHours.Text);
                        var minutes = string.IsNullOrEmpty(this.durationTextBoxMinutes.Text) ? 0 : Int16.Parse(this.durationTextBoxMinutes.Text);
                        var seconds = string.IsNullOrEmpty(this.durationTextBoxSeconds.Text) ? 0 : Int16.Parse(this.durationTextBoxSeconds.Text);
                        var distance = string.IsNullOrEmpty(this.distanceTextBox.Text) ? 0 : Int64.Parse(this.distanceTextBox.Text.Replace(".","").Replace(",","").PadRight(4,'0'));
                        this.suuntoWorkout = new Workout(startDate, activity, hours, minutes, seconds, this.commentTextBox.Text);
                        this.suuntoWorkout.DistanceInMeters = distance;
                    }
                    catch (Exception ex)
                    {
                        this.createdWorkoutLog.Text = "Verify user defined input data! " + ex.Message;
                        return;
                    }                    
                }
           } 

            try
            {
                var endomondoWebDriver = EndomondoWebDriver.Create(EndomondoWebDriver.WebDriverType.Firefox);
                endomondoWebDriver.Login(this.usernameTextBox.Text, this.passwordTextBox.Password);
                endomondoWebDriver.NavigateToManualWorkoutSite();
                endomondoWebDriver.CreateManualWorkout(suuntoWorkout);
                endomondoWebDriver.Close();
                this.createdWorkoutLog.Text = "The workout has been successfully created";
            }
            catch (Exception ex)
            {
                this.createdWorkoutLog.Text = ex.Message;
                return;
            }           
        }
    }
}
